use uuid::Uuid;

use async_graphql::{Error, ErrorExtensions};
use rbatis::rbatis::Rbatis;
use rbatis::crud::CRUD;

use crate::util::constant::GqlResult;
use crate::features::dict::modelsdbo::{NewWord, WordDBO};

// 查询所有用户
pub async fn all_wordens(rbatis_pool: &Rbatis) -> GqlResult<Vec<WordDBO>> {
    let wordens = rbatis_pool.fetch_list::<WordDBO>().await.unwrap();

    if wordens.len() > 0 {
        Ok(wordens)
    } else {
        Err(Error::new("1-all-wordens")
            .extend_with(|_, e| e.set("details", "No records")))
    }
}

// 通过 email 获取用户
pub async fn get_worden_by_email(
    rbatis_pool: &Rbatis,
    email: &str,
) -> GqlResult<WordDBO> {
    let email_wrapper = rbatis_pool.new_wrapper().eq("email", email);
    let worden = rbatis_pool.fetch_by_wrapper::<WordDBO>(email_wrapper).await;

    if worden.is_ok() {
        Ok(worden.unwrap())
    } else {
        Err(Error::new("email 不存在")
            .extend_with(|_, e| e.set("details", "1_EMAIL_NOT_EXIStS")))
    }
}

// 插入新用户
pub async fn new_worden(
    rbatis_pool: &Rbatis,
    mut new_worden: NewWord,
) -> GqlResult<WordDBO> {
    new_worden.email = new_worden.email.to_lowercase();

    if self::get_worden_by_email(rbatis_pool, &new_worden.email).await.is_ok() {
        Err(Error::new("email 已存在")
            .extend_with(|_, e| e.set("details", "1_EMAIL_EXIStS")))
    } else {
        new_worden.cred =
            "P38V7+1Q5sjuKvaZEXnXQqI9SiY6ZMisB8QfUOP91Ao=".to_string();
        
        let my_uuid = Uuid::new_v4();

        new_worden.id = my_uuid.to_simple().to_string();

        // rbatis_pool.save(&new_worden).await.expect("插入 worden 数据时出错");

        self::get_worden_by_email(rbatis_pool, &new_worden.email).await
    }
}
